#!/bin/sh

usage()
{
    echo "Usage: fmainframe.sh idExp inFile outputDir [operationMask]" 2>&1
    echo "[operationMask]" 2>&1
    echo "		none:	all (11)" 2>&1
    echo "		1x	:	identify" 2>&1
    echo "		x1	:	factorize" 2>&1
	
    exit $E_PARAMERR  # Not enough arguments passed to script.
}

job(){
	
	if [ $identify -eq 1 ] ; then

                results=`./mainframe $number &`

                result=`echo $results | cut -f 2 -d ","`

                if [ $result != "noperfect" ] ; then
                        echo $result >> $path.perfect
                        echo "perfect!" 
                else
                        echo "no perfect :("
                fi

                result=`echo $results | cut -f 3 -d ","`
                if [ $result != "noprime" ] ; then
                        echo $result >> $path.prime
                        echo "prime!"   
                else
                        echo "no prime :("
                fi

                result=`echo $results | cut -f 4 -d ","`
                if [ $result != 'nopalindrome' ] ; then
                        echo $result >> $path.palindrome
                        echo "palindrome!"      
                else
                        echo "no palindrome :("
                fi
        else
                echo "Identify $number skipped."
        fi

        if [ $factorize -eq 1 ] ; then

                factors=`factor $number &`

                echo "factorize $factors"
                echo $factors >> $path.factors
        else
                echo "Factorize $number skipped"
        fi

        echo $results | cut -f 1 -d "," >> $path.done
        echo "<<< $number done!"
}

if [ -z "$1" ] ; then
    echo "$1: Please set a experiment id." 2>&1
    usage                 # Print usage message and exit.
else
	id=$1
fi 

if [ ! -f "$2" ] ; then
    echo "$2: Please set a valid number list." 2>&1
    usage                 # Print usage message and exit.
else
	file=$2
fi 

if [ -z "$3" ] ; then
    echo "$3: No such folder." 2>&1
    usage
else
	output=$3
fi

if [ -z $4 ] ; then
	op=11;	
else
	## TODO : Checkear $4
	op=$4;
fi

identify=`echo $op | cut -b1`;
factorize=`echo $op | cut -b2`;

output=`echo $output | sed 's/[\/]//g'`

if [ -d `echo $output/$id` ] ; then 
	id=$id.`date +%s`
fi

mkdir -p $output/$id

path=`echo "$output/$id/$id"`

echo "Experiment #$id"
echo "----------------"
echo "output: $path.*"
echo "input : $file" 
echo "op 	: $op"
echo "----------------"

if [ -z $5 ] ; then
       	maxjobs=4 
else
	maxjobs=$5
fi

cjobs=0
ncount=0
ntotal=`wc -l < $file`

exec < $file
while read number
do

	while  [ $cjobs -ge $maxjobs ] ; do
		wait
		cjobs=`expr $cjobs - 1`
	done
	
	job > /dev/null &

	cjobs=`expr $cjobs + 1`
	ncount=`expr $ncount + 1`

	status=`expr $ncount \* 100`
	status=`echo "scale=2; $status/$ntotal" | bc`

	echo "Launch status : $ncount of $ntotal [ $status % ] [$cjobs of $maxjobs running in parallel]"

done
